#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/11/28 10:26
# @Author  : FuKai ZHANG
# @File    : windows_switch.py
# @Description :浏览器窗口切换操作

from utils.Logging_tools.log_control import INFO
from selenium.common.exceptions import NoSuchWindowException


class WindowsSwitch:
    def __init__(self, driver):
        self.driver = driver

        # 获取当前打开的所有窗口句柄列表
        self.windows_handles = self.driver.window_handles

    def switch_to_window(self, window_number: int, model=None):
        """
        切换到指定窗口
        :param window_number: 窗口位置，从1开始
        :return:
        """
        if window_number < 1 or window_number > int(len(self.windows_handles)):
            raise Exception(f"不支持{window_number}窗口索引")
        # 判断窗口是否打开
        if 1 <= window_number <= len(self.windows_handles):
            INFO.info(f"切换到窗口{model}")

            self.driver.switch_to.window(self.windows_handles[window_number - 1])
        else:
            raise NoSuchWindowException(f"窗口{model}未打开")

    def switch_to_first_window(self):
        """
        切换到第一个窗口
        :return:
        """
        self.driver.switch_to.window(self.windows_handles[0])

    def switch_to_last_window(self):
        """
        切换到最后一个窗口
        :return:
        """
        self.driver.switch_to.window(self.windows_handles[-1])